<template>
  <div class="app-container">
    <el-card>
      <el-steps :active="stepActive" simple finish-status="success">
        <el-step title="1 编辑基本信息" />
        <el-step title="2 编辑商品详情" />
      </el-steps>
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="110px">
        <div v-show="stepActive === 1">
          <title-line title="商品类型" />

          <div style="position: relative">
            <el-form-item label-width="0" prop="type" class="pl-20">
              <el-radio-group v-model="formData.type" @change="resetFormData">
                <el-radio :label="1">自营商品</el-radio>
                <el-radio :label="3">第三方商品</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 供应链下拉表 -->
            <el-form-item
              style="position: absolute; top: 0; left: 240px"
              v-if="formData.type === 3"
              label-width="0"
              prop="supplyId"
              class="pl-20"
            >
              <el-select
                v-model="formData.supplyId"
                clearable
                placeholder="请选择供应链"
                @change="supplyIdChange"
              >
                <el-option
                  v-for="item in supplyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div>

          <title-line title="商品分类" />
          <el-form-item label="" label-width="20px" prop="categoryId">
            <el-cascader
              v-model="formData.categoryId"
              :options="classifyList"
              :props="categoryProps"
              placeholder="请选择商品分类"
              clearable
            ></el-cascader>
          </el-form-item>

          <title-line title="基本信息" />

          <el-row>
            <el-col :lg="14" :xl="10">
              <!-- 供应链商品显示（聚合供应链） -->
              <el-form-item
                v-if="supplyCode === 'JuHe' && formData.type === 3"
                label="SPUID："
                prop="supplySpuId"
              >
                <el-input
                  v-model="formData.supplySpuId"
                  @blur="validSup"
                  :disabled="loading"
                  placeholder="请输入SPUID"
                />
                <div v-if="loading">
                  <i class="el-icon-loading"></i>
                  <span>正在同步数据，请稍后......</span>
                </div>
                <p class="ft-12" style="color: #999">用于第三方供应链商品库存同步</p>
              </el-form-item>

              <!-- 供应链商品编号（盛创供应链） -->
              <el-form-item
                v-if="supplyCode === 'ShengChuang' && formData.type === 3"
                label="商品编号："
                prop="goodsNumCode"
              >
                <el-input
                  v-model="formData.goodsNumCode"
                  @blur="validGoodsNumCode"
                  :disabled="loading"
                  placeholder="请输入商品编号"
                />
                <div v-if="loading">
                  <i class="el-icon-loading"></i>
                  <span>正在同步数据，请稍后......</span>
                </div>
                <p class="ft-12" style="color: #999">用于第三方供应链商品库存同步</p>
              </el-form-item>

              <el-form-item label="商品名称：" prop="name">
                <el-input
                  v-model="formData.name"
                  :disabled="loading"
                  placeholder="请输入商品名称50字以内"
                />
              </el-form-item>

              <!-- 供应链商品显示 -->
              <el-form-item v-if="supplyCode && formData.type === 3" label="商品名称（供应链）：">
                <el-input v-model="goodsSupplyName" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品相册：" prop="images">
            <UploadImage
              ref="uploadImage"
              :isShowTip="true"
              :file-type="['jpg', 'png', 'jpeg']"
              file-pixel="800*800"
              :file-size="1"
              :limit="8"
              :disabled="loading"
              :multiple="true"
              @on-change="uploadImageChange"
              v-model="formData.images"
            />
          </el-form-item>

          <el-row>
            <el-col :lg="14" :xl="10">
              <el-form-item label="商品视频：" prop="video">
                <UploadVideo
                  :isShowTip="true"
                  :lazy="true"
                  :file-size="50"
                  :disabled="loading"
                  :file-type="['mp4']"
                  v-if="!formData.video"
                  v-model="formData.video"
                />
                <div class="video-box" v-else>
                  <VideoPlayer :sources-data="videoSource" />
                  <el-button class="delete-btn" type="text" @click="deleteVideo">删除</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="供应商：" prop="supplierId">
            <ScrollSelect
              style="width: 300px"
              placeholder="请选择供应商"
              :selected-value="formData.supplierId"
              :get-list-methods="getListMethods"
              :get-list-format="getListFormat"
              :page-sizes="supplierTotal"
              :clearable="true"
              search-key="name"
              @selectedChange="selectedChange"
            />
          </el-form-item>

          <el-form-item label="商品品牌：" prop="brandId">
            <!-- <AddSelectBrand v-model="formData.brandId" /> -->
            <ScrollSelect
              style="width: 300px"
              placeholder="请选择商品品牌"
              :selected-value="formData.brandId"
              :get-list-methods="getBrandListMethods"
              :get-list-format="getListFormat"
              :page-sizes="brandTotal"
              :clearable="true"
              search-key="name"
              @selectedChange="selectedBrandChange"
            />
          </el-form-item>

          <title-line title="价格库存" />
          <el-form-item label="售价方式：" required>
            <el-radio-group v-model.number="formData.priceType" @change="handleChangePriceType">
              <el-radio :label="1">纯积分</el-radio>
              <el-radio :label="2">积分+现金/代金券</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- sku生成 -->
          <el-row>
            <el-col :lg="24" :xl="22">
              <AddSelectSku
                v-if="skuSelectList.length"
                ref="selectSku"
                :type="formData.type"
                :supply-code="supplyCode"
                :skuSelectList="skuSelectList"
                :spu-id="formData.supplySpuId"
                :priceType="formData.priceType"
              />
            </el-col>
          </el-row>

          <el-row class="mt-30">
            <el-col :lg="14" :xl="10">
              <el-form-item label="库存预警：" prop="stockWarningQuantity">
                <el-input
                  placeholder="请输入库存预警"
                  :maxlength="3"
                  v-model.number="formData.stockWarningQuantity"
                />
                <p class="ft-12" style="color: #999999">库存达到预警值系统会进行提醒</p>
              </el-form-item>

              <el-form-item label="商品编码：" prop="code">
                <el-input placeholder="请输入商品编码" v-model="formData.code" />
              </el-form-item>

              <el-form-item label="虚拟销量" prop="virtualSalesQuantity">
                <el-input
                  :maxlength="4"
                  placeholder="请输入虚拟销量"
                  v-model.number="formData.virtualSalesQuantity"
                />
                <p class="ft-12" style="color: #999999">后台填充虚拟销售数据</p>
              </el-form-item>
            </el-col>
          </el-row>

          <title-line title="配送方式" />
          <el-form-item label="配送方式：" required>
            <el-radio-group v-model="formData.distributionMode">
              <el-radio v-for="(item, index) in SEND_STATUS" :key="index" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="运费模板：" prop="expressTemplateId">
            <AddSelectTemplate v-model="formData.expressTemplateId" />
          </el-form-item>

          <title-line title="其他信息" />
          <el-form-item label="商品标签：" prop="tagIds">
            <el-checkbox-group v-model="formData.tagIds">
              <el-checkbox v-for="item in tagList" :key="item.id" :label="item.id">{{
                item.name
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="购买限制：" prop="buyLimit">
            <el-radio-group v-model="isBuyLimit" @change="buyLimitChange">
              <el-radio :label="false"> 不限制 </el-radio>
              <el-radio :label="true"> 限制购买数量 </el-radio>
            </el-radio-group>

            <template v-if="isBuyLimit">
              <el-input
                class="ml-10"
                style="width: 20%"
                v-model.number="formData.buyLimit"
                placeholder="限购数量"
              ></el-input>
              <span class="ml-10">件</span>
            </template>
          </el-form-item>

          <el-form-item label="推荐到列表：" required>
            <el-radio-group v-model="formData.isSortCategory">
              <el-radio v-for="(item, index) in RECOMMMEND" :key="index" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="推荐到首页：" required>
            <el-radio-group v-model="formData.isSortHome">
              <el-radio v-for="(item, index) in RECOMMMEND" :key="index" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="上架平台" prop="platform">
            <el-checkbox-group v-model="formData.platform" size="medium">
              <el-checkbox
                v-for="(item, index) in Object.keys(OPEN_PLATFORM)"
                :key="index"
                :label="item"
                >{{ OPEN_PLATFORM[item] }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>

          <el-row>
            <el-col :lg="12" :xl="10">
              <el-form-item label="商品排序：" prop="sort">
                <el-input v-model="formData.sort" />
              </el-form-item>
              <el-form-item label="商品备注：" prop="remake">
                <el-input
                  v-model="formData.remake"
                  :disabled="loading"
                  placeholder="请输入备注，2到15字以内"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item class="text-center">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click="submitNextPage">下一步</el-button>
          </el-form-item>
        </div>

        <!-- 商品详情 -->
        <div v-if="stepActive === 2">
          <el-form-item class="mt-30" label-width="0" prop="details">
            <Tinymce v-model="formData.details" />
          </el-form-item>
          <el-form-item class="text-center">
            <el-button @click="submitPrevPage">上一步</el-button>
            <el-button @click="submitForm" type="primary">确定</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
import rules from './rules-mixin'
import { SUPPLY_TYPE } from '@/enum'
import { OPEN_PLATFORM } from '@/enum/goods'
import { useGenerateUUID } from '@/hooks/index'
import { SEND_STATUS, RECOMMMEND } from '@/enum'
import AddSelectSku from './components/AddSelectSku.vue'
import AddSelectBrand from './components/AddSelectBrand.vue'
import AddSelectTemplate from './components/AddSelectTemplate.vue'
export default {
  name: 'AddGoods',
  components: {
    AddSelectSku,
    AddSelectBrand,
    AddSelectTemplate
  },
  mixins: [rules],
  data() {
    return {
      // 分类级联配置项
      categoryProps: {
        // emitPath: false,
        checkStrictly: true,
        value: 'id',
        label: 'name',
        children: 'childList'
      },
      // 分类列表
      classifyList: [],
      // 供应链列表
      supplyList: [],
      // 供应链code
      supplyCode: '',
      // 供应商列表
      suplierList: [],
      // 标签列表
      tagList: [],
      // 规格值列表
      skuSelectList: [],
      // 当前位于步骤
      stepActive: 1,
      // 是否限购
      isBuyLimit: false,
      // 供应商下拉搜索方法
      getListMethods: params => {
        return this.getSuplier(params)
      },
      // 品牌列表
      brandList: [],
      // 品牌下拉搜索方法
      getBrandListMethods: params => {
        return this.getBrandList(params)
      },
      // 表单
      formData: {
        //商品备注
        remake: '',
        // 商品类型 [1: 自营商品, 2: 新人专区商品, 3: 供应链商品]
        type: 1,
        goodsId: '',
        // 商品分类id
        categoryId: [],
        // 商品名称
        name: '',
        // 商品相册
        images: [],
        // 商品视频
        video: '',
        // 供应商id,
        supplierId: '',
        // 供应链Id
        supplyId: '',
        // 供应链名称
        supplyName: '',
        // 品牌id
        brandId: '',
        // 配送方式 [1: 快递配送, 2: 门店自提],可用值:1,2
        distributionMode: 1,
        // 快递模板id
        expressTemplateId: '',
        // 商品标签
        tagIds: [],
        // spuid
        supplySpuId: '',
        // 库存预警值
        stockWarningQuantity: '',
        // 购买限制 0-无限制
        buyLimit: 0,
        // 推荐到列表
        isSortCategory: false,
        // 推荐到首页
        isSortHome: false,
        // 上架平台
        platform: [],
        // 商品编码
        code: '',
        // 虚拟销量
        virtualSalesQuantity: _.random(1, 1000),
        // 排序
        sort: 99,
        // 商品详情
        details: '',
        // 商品规格明细
        skuList: [],
        // 商品规格关系
        specRelation: {},
        // 商品编号（盛创供应链supId）
        goodsNumCode: '',

        // 商品售货类型 [1: 积分销售, 2: 积分+现金]
        priceType: 1
      },
      // 同步数据时禁止输入
      loading: false,
      // 商品供应链名称
      goodsSupplyName: '',
      // 是否有库存
      verifyStock: true,
      // 供应商总数
      supplierTotal: 1000,
      // 品牌总数
      brandTotal: 1000
    }
  },
  computed: {
    // 配送方式
    SEND_STATUS() {
      return SEND_STATUS
    },
    // 推荐状态
    RECOMMMEND() {
      return RECOMMMEND
    },
    // 上架平台
    OPEN_PLATFORM() {
      return OPEN_PLATFORM
    },
    videoSource() {
      return [this.formData.video]
    }
  },
  watch: {
    // 监听是否限购
    isBuyLimit(value) {
      if (!value) {
        this.formData.buyLimit = 0
      }
    },
    // 盛创供应链只显示默认规格
    supplyCode(value) {
      if (value === 'ShengChuang' && this.formData.type === 3) {
        this.skuSelectList = this.skuSelectList.filter(item => item.id === '1000000000000000001')
      }
    },
    // 商品类型 [1: 自营商品, 2: 新人专区商品, 3: 供应链商品]
    'formData.type'(value) {
      if (value === 1) {
        this.formData.supplyId = ''
      }
    },
    'formData.brandId'(value) {
      if (value) {
        this.$refs.elForm.clearValidate('brandId')
      }
    },
    'formData.platform'(value) {
      if (value.length) {
        this.$refs.elForm.validateField('platform')
      }
    },
    'formData.tagIds'(value) {
      if (value.length) {
        this.$refs.elForm.validateField('tagIds')
      }
    },
    skuSelectList(value) {
      console.log(value)
    }
  },
  async created() {
    await this.getSpecList()
    // 获取商品详情
    this.getGoodsInfo()
    // 获取供应链列表
    this.getSupplyList()
    // 获取分类列表
    this.getClassify()
    // 获取标签列表
    this.getTags()
  },
  methods: {
    handleChangePriceType() {
      console.log('value', this.$refs.selectSku.formData)
      // if (this.$refs.selectSku.formData.skuList[0].money) {
      //   this.$refs.selectSku.formData.skuList[0].money = ''
      // }
      // this.$refs.selectSku.formData.skuList[0].money = ''
    },
    getListFormat: (list = []) => {
      // 下拉框数据格式
      return list.map(({ name, id }) => ({
        label: name,
        value: id
      }))
    },
    // 获取供应商id
    selectedChange(id) {
      this.formData.supplierId = id
    },

    // 获取品牌id
    selectedBrandChange(id) {
      this.formData.brandId = id
    },

    // 获取品牌列表
    async getBrandList(params = {}) {
      try {
        const { data } = await this.$http.goods.brand.page({ params })
        this.brandTotal = data.total
        return (this.brandList = data.records.filter(item => {
          return item.isShow
        }))
      } catch (error) {}
    },
    // 获取规格值列表
    async getSpecList() {
      try {
        const {
          data: { records }
        } = await this.$http.goods.spec.page({ params: { pageNo: 1, pageSize: 10 } })
        this.skuSelectList = records.filter(item => {
          return item.isShow
        })
      } catch (error) {
        console.log('getSpecList', error)
      }
    },

    // 获取商品详情
    async getGoodsInfo() {
      if (!this.$route.query.id) return

      try {
        const { data } = await this.$http.goods.goods.getById({
          params: { id: this.$route.query.id }
        })

        console.log('data', data)

        // 规格下拉列表赋值
        this.$refs.selectSku.skuList = [
          {
            name: this.skuSelectList.find(el => el.id === data.specRelation.specOneId)?.name,
            id: useGenerateUUID(),
            item: data.specRelation.specOneValues.map(el => ({ value: el, id: useGenerateUUID() }))
          }
        ]
        if (data.specRelation.specTwoId && data.specRelation.specTwoValues.length) {
          this.$refs.selectSku.skuList.push({
            name: this.skuSelectList.find(el => el.id === data.specRelation.specTwoId)?.name,
            id: useGenerateUUID(),
            item: data.specRelation.specTwoValues.map(el => ({ value: el, id: useGenerateUUID() }))
          })
        }
        const specList = this.$lodash.cloneDeep(this.$refs.selectSku.skuList)
        // sku列表赋值
        this.$refs.selectSku.formData.skuList = data.skuList.map(el => {
          const specOne = specList[0].item.find(item => item.value === el.specOneValue)
          let specTow = null
          if (el.specTwoValue) {
            specTow = specList[1].item.find(item => item.value === el.specTwoValue)
          }
          const key = el.specTwoValue ? specOne.id + '_' + specTow.id : specOne.id
          const attrSet = [
            { label: specList[0].name, specItemId: specOne.id, value: specOne.value }
          ]
          if (el.specTwoValue) {
            specList[1].item.find(item => item.value === el.specTwoValue)
            attrSet.push({
              label: specList[1].name,
              specItemId: specTow.id,
              value: specTow.value
            })
          }
          return {
            attrSet,
            key,
            ...el,
            price: Number(el.price)
          }
        })
        this.$refs.selectSku.createTempMergeIndex()

        // 回显赋值
        for (const key in data) {
          this.formData[key] = data[key]
        }

        this.isBuyLimit = this.formData.buyLimit ? true : false
        this.formData.platform = this.formData.platform.split(',')
        this.formData.categoryId = [
          data.categoryOneId,
          data.categoryTwoId,
          data.categoryThreeId
        ].filter(item => item)

        // 选中供应链
        this.supplyCode = this.supplyList.find(item => item.id === this.formData.supplyId)?.code

        // 盛创商品回显商品编码
        if (this.formData.type === 3 && this.supplyCode === 'ShengChuang') {
          this.formData.goodsNumCode = this.formData.supplySpuId
        }

        // 商品供应链名称
        this.goodsSupplyName = this.formData.name
      } catch (error) {
        console.log('getGoodsInfo', error)
      }
    },

    // 获取供应商列表
    async getSuplier(params = {}) {
      const {
        data: { records, total }
      } = await this.$http.goods.supplier.page({ params })
      this.supplierTotal = total
      return records
    },

    // 获取供应链列表
    async getSupplyList() {
      try {
        const { data } = await this.$http.supply.getSelectList()
        this.supplyList = data
      } catch (error) {
        console.log('getSupplyList', error)
      }
    },

    // 切换供应链类型，清空数据
    resetFormData() {
      this.formData.name = ''
      this.formData.video = ''
      this.goodsSupplyName = ''
      this.formData.supplySpuId = ''
      this.formData.goodsNumCode = ''
      this.formData.details = ''
      this.formData.images = []
      this.$refs.elForm.clearValidate()
      this.$refs.selectSku.renderSkuList(true)
      this.$refs.selectSku.$refs.skuForm.clearValidate()
    },

    // 根据供应链id查询code, 根据code显示不同的供应链表单项
    supplyIdChange(id) {
      if (id) {
        this.supplyCode = this.supplyList.find(item => item.id === id)?.code
      } else {
        this.supplyCode = ''
      }

      // 切换供应链清空数据
      this.resetFormData()
    },

    // 获取分类列表
    async getClassify() {
      try {
        const { data } = await this.$http.goods.classify.getCategorySelectList()
        this.classifyList = data
      } catch (error) {
        console.log('getClassify', error)
      }
    },

    // 获取标签列表
    async getTags() {
      try {
        const { data } = await this.$http.goods.tag.list()
        this.tagList = data.filter(item => {
          return item.isShow
        })
      } catch (error) {
        console.log('getTags', error)
      }
    },

    // 验证spuid
    validSup() {
      if (!this.formData.supplySpuId) {
        this.resetFormData()
        return
      }
      this.loading = true
      this.$http.supply
        .valid({
          params: {
            goodsSupply: SUPPLY_TYPE[this.supplyCode],
            spuId: this.formData.supplySpuId
          }
        })
        .then(res => {
          if (res.status === 200) {
            const { title, covers, cover, description } = res.data
            this.loading = false
            this.formData.name = title
            this.goodsSupplyName = title
            this.formData.details = description
            this.formData.images = [cover, ...covers]
          }
        })
        .catch(error => {
          this.resetFormData()
          this.loading = false
          this.$message.error(error.data.msg)
        })
    },

    // 盛创验证商品编号
    validGoodsNumCode() {
      if (!this.formData.goodsNumCode) {
        this.resetFormData()
        return
      }

      this.loading = true
      this.$http.supply
        .valid({
          params: {
            goodsSupply: SUPPLY_TYPE[this.supplyCode],
            skuId: this.formData.goodsNumCode,
            spuId: this.formData.goodsNumCode
          }
        })
        .then(res => {
          if (res.status === 200) {
            const { title, covers, cover, description, options } = res.data
            this.loading = false
            this.formData.name = title
            this.goodsSupplyName = title
            this.formData.details = JSON.parse(description).reduce((prev, current) => {
              return `<img src=${current}></img>` + prev
            }, '')
            this.formData.images = [cover, ...covers]

            this.formData.video = options[0]?.goodsVideo
            this.formData.supplySpuId = this.formData.goodsNumCode

            this.$refs.selectSku.formData.skuList = this.$refs.selectSku.formData.skuList.map(
              el => {
                return {
                  ...el,
                  supplyState: Boolean(options[0]?.status),
                  mainGraph: options[0]?.image,
                  stockQuantity: options[0]?.stock,
                  weight: options[0]?.weight,
                  supplySkuId: this.formData.goodsNumCode
                }
              }
            )
          }
        })
        .catch(error => {
          this.resetFormData()
          this.loading = false
          this.$message.error(error.data.msg)
        })
    },

    buyLimitChange() {
      this.$refs.elForm.clearValidate('buyLimit')
    },

    uploadImageChange() {
      if (this.formData.goodsImgUrl) {
        this.$refs.elForm.validateField('goodsImgUrl')
      }
    },
    uploadVideoChange() {
      if (this.formData.video) {
        this.$refs.elForm.validateField('video')
      }
    },
    deleteVideo() {
      this.formData.video = ''
    },
    // 上一步
    submitPrevPage() {
      this.stepActive = 1
    },
    // 下一步
    submitNextPage() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return this.$message.error('有必填项未填写')
        let skuValid = true
        // 验证sku模块相关
        this.$refs.selectSku.skuList.forEach(el => {
          if (!el.name) {
            this.$message.error('请选择规格名称')
            skuValid = false
          }
          el.item.forEach(item => {
            if (!item.value) {
              this.$message.error('请输入规格值')
              skuValid = false
            }
          })
        })
        if (!skuValid) return
        // 参数整合
        this.$refs.selectSku.$refs.skuForm.validate(valid => {
          if (!valid) return
          this.stepActive = 2
        })
      })
    },
    resetForm() {
      this.$router.back(-1)
      this.$refs['elForm'].resetFields()
    },

    // 新增提交商品
    submitForm() {
      // 参数整合
      const params = this.$lodash.cloneDeep(this.formData)

      // 删除盛创供应链商品编号（supuId）
      if (params.goodsNumCode) delete params.goodsNumCode

      // 取最后一级
      params.categoryId = params.categoryId[params.categoryId.length - 1]

      console.log(params, this.supplyCode)

      // 验证是否有库存（聚合为false）
      if (params.type === 3 && this.supplyCode === 'JuHe') {
        params.verifyStock = false
      } else {
        params.verifyStock = true
      }

      const blackFiles = [
        'categoryOneId',
        'categoryOneName',
        'categoryTwoId',
        'categoryTwoName',
        'categoryThreeId',
        'categoryThreeName'
      ]
      for (let key in params) {
        if (blackFiles.includes(key)) {
          delete params[key]
        }
      }

      // sku参数处理
      params.skuList = this.$refs.selectSku.formData.skuList
      // if (params.priceType == 1) {
      //   params.skuList = params.skuList.map(el => ({
      //     ...el,
      //     money: ''
      //   }))
      // }

      params.specRelation = {}
      params.specRelation.specOneId = this.$refs.selectSku.skuSelectList.find(
        el => el.name === this.$refs.selectSku.skuList[0].name
      ).id
      params.specRelation.specOneValues = this.$refs.selectSku.skuList[0].item.map(el => el.value)
      if (this.$refs.selectSku.skuList.length > 1) {
        params.specRelation.specTwoId = this.$refs.selectSku.skuSelectList.find(
          el => el.name === this.$refs.selectSku.skuList[1].name
        ).id
        params.specRelation.specTwoValues = this.$refs.selectSku.skuList[1].item.map(el => el.value)
      }
      params.platform = params.platform.join(',')
      if (this.formData.type === 3) {
        params.supplyName = this.supplyList.find(el => el.id === params.supplyId).name
      }
      // 是否编辑商品
      const id = this.$route.query.id
      // 请求api
      let api = 'save'
      if (id) {
        params.id = id
        params.specRelation.id = this.formData.specRelation.id
        api = 'edit'
      }
      // 发送网络请求
      this.$http.goods.goods[api](params)
        .then(res => {
          // console.log(res)
          if (res.status === 200) {
            const message = id ? '编辑成功' : '新增成功'
            this.$message.success(message)
            this.$router.back()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.video-box {
  position: relative;
}
.delete-btn {
  position: absolute;
  z-index: 9999;
  top: 20px;
  right: 20px;
  background: #fff;
  padding: 5px;
}
</style>
